package com.pospi.xstore.ui.report;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.DialogFragment;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jzxiang.pickerview.TimePickerDialog;
import com.jzxiang.pickerview.data.Type;
import com.jzxiang.pickerview.listener.OnDateSetListener;
import com.lany.sp.SPHelper;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.mylhyl.circledialog.CircleDialog;
import com.mylhyl.circledialog.params.ProgressParams;
import com.pospi.xstore.R;
import com.pospi.xstore.dto.CustomerBeen;
import com.pospi.xstore.dto.KcBill;
import com.pospi.xstore.dto.StoreBeen;
import com.pospi.xstore.dto.SupBeen;
import com.pospi.xstore.http.LoadServer;
import com.pospi.xstore.ui.base.BaseActivity;
import com.pospi.xstore.ui.caigou.CgddBeen;
import com.pospi.xstore.ui.caigou.InventorySearchActivity;
import com.pospi.xstore.ui.caigou.SupActivity;
import com.pospi.xstore.util.Api;
import com.pospi.xstore.util.Constant;
import com.pospi.xstore.util.GetData;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
/*
* 门店经营查询
* */

public class StoreReportSearchActivity extends BaseActivity {
    @Bind(R.id.cgmd)
    TextView md;
    @Bind(R.id.time_start_select)
    TextView time_start_select;
    @Bind(R.id.time_end_select)
    TextView time_end_select;
    private SupBeen supBeen = new SupBeen();
    private String count;
    private String je;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentLayout(R.layout.store_report_search);
        ButterKnife.bind(this);
        setTitle("高级查询");
        time_start_select.setText(GetData.getYYMMDDTime());
        time_end_select.setText(GetData.getYYMMDDTime());
        down();
        downpp();
        downmd();

    }






    List<String> strings = new ArrayList<>();
    @OnClick({R.id.cgmd,R.id.bt_search,R.id.time_start_select,R.id.time_end_select})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.cgmd:
                strings.clear();
                for (SupBeen been : md_Beens) {
                    strings.add(been.getName());
                }
                creatDialogMarket(strings);
                break;
            case R.id.bt_search:
                Intent intent1 = new Intent(StoreReportSearchActivity.this,StoreReportActivity.class);
                intent1.putExtra("startrq", time_start_select.getText().toString());
                intent1.putExtra("endrq", time_end_select.getText().toString());
                intent1.putExtra("market", market);
                intent1.putExtra("marketname", marketname);
                startActivity(intent1);
                break;
            case R.id.time_start_select:
                TimePickerDialog dialogYearMonthDay = new TimePickerDialog.Builder()
                        .setType(Type.YEAR_MONTH_DAY)
                        .setTitleStringId("选择日期")
                        .setWheelItemTextSize(16)
                        .setCallBack(new OnDateSetListener() {
                            @Override
                            public void onDateSet(TimePickerDialog timePickerView, long millseconds) {
                                Date date = new Date(millseconds);
                                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                                String time = format.format(date);
                                time_start_select.setText(time);
                            }
                        })
                        .build();
                dialogYearMonthDay.show(getSupportFragmentManager(), "YEAR_MONTH_DAY");
                break;
            case R.id.time_end_select:
                TimePickerDialog dialogYearMonthDay2 = new TimePickerDialog.Builder()
                        .setType(Type.YEAR_MONTH_DAY)
                        .setTitleStringId("选择日期")
                        .setWheelItemTextSize(16)
                        .setCallBack(new OnDateSetListener() {
                            @Override
                            public void onDateSet(TimePickerDialog timePickerView, long millseconds) {
                                Date date = new Date(millseconds);
                                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                                String time = format.format(date);
                                time_end_select.setText(time);
                            }
                        })
                        .build();
                dialogYearMonthDay2.show(getSupportFragmentManager(), "YEAR_MONTH_DAY");
                break;
        }
    }


    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    close();
                    Intent intent1 = new Intent(StoreReportSearchActivity.this,StoreReportActivity.class);
                    intent1.putExtra("startrq", time_start_select.getText().toString());
                    intent1.putExtra("endrq", time_end_select.getText().toString());
                    intent1.putExtra("market", market);
                    startActivity(intent1);
                    break;
                case 2:

                    break;
                case 3:

                    break;
                case 4:

                    break;
            }

        }
    };

    List<KcBill> bills = new ArrayList<>();
    private void searchBill() {
        showDialog();
        RequestParams params = new RequestParams();
        params.put("logid", SPHelper.getInstance().getString(Constant.USER_ID));
        params.put("sysid", SPHelper.getInstance().getString(Constant.SYS_ID));
        params.put("model", "report.mkcbb");
        params.put("fun", "find_spkchz");

//        params.put("page", "");
//        params.put("limit", "");


        JSONObject object = new JSONObject();
        try {

            object.put("catid", cat);
            object.put("market", market);
            object.put("supid", supBeen.getId());
            object.put("brandid", brand);
//            object.put("filter", "");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        params.put("pds", object.toString());
        Log.i("login",params.toString());
        LoadServer.getConnect(getApplicationContext(), Api.LOGIN, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int i, Header[] headers, byte[] bytes) {
                Log.i("login", new String(bytes));
                try {
                    JSONObject jsonObject = new JSONObject(new String(bytes));
                    JSONArray result = jsonObject.getJSONArray("result");
                    Log.i("login", jsonObject.getString("errMsg"));
                    count = jsonObject.getString("count");
                    je = jsonObject.getJSONObject("sumrow").getString("jjje");
                    if (result.length() > 1) {
                        for (int j=0;j<result.length()-1;j++) {
                            JSONObject data = result.getJSONObject(j);
                            KcBill kcBill = new KcBill();
                            kcBill.setName(data.getString("name"));
                            kcBill.setBarcode(data.getString("barcode"));
                            kcBill.setJj(data.getString("jj"));
                            kcBill.setLsj(data.getString("lsj"));
                            kcBill.setPfj(data.getString("pfj"));

                            kcBill.setKcsl(data.getString("kcsl"));
                            kcBill.setKcjs(data.getString("kcjs"));
                            kcBill.setJjje(data.getString("jjje"));
                            bills.add(kcBill);
                        }
                    }
                    Message message = Message.obtain();
                    message.what = 1;
                    handler.sendMessage(message);
                } catch (JSONException e) {

                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
                Message message = Message.obtain();
                message.what = 3;
                handler.sendMessage(message);
            }
        });
    }

    private String market = "";
    private String cat = "";
    private String brand = "";
    private String marketname = "";
    private void creatDialogMarket(final List<String> ss) {

        new CircleDialog.Builder(this)
                .setItems(ss, new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                        //门店
                        md.setText(ss.get(i));
                        market = md_Beens.get(i).getId();
                        marketname = md_Beens.get(i).getName();

                    }
                })
                .setGravity(Gravity.CENTER)
                .show();
    }




    private List<SupBeen> fl_Beens = new ArrayList<>();//分类
    private List<SupBeen> pp_Beens = new ArrayList<>();//品牌
    private List<SupBeen> md_Beens = new ArrayList<>();//门店
    //下载分类
    private void down() {
        RequestParams params = new RequestParams();
        params.put("logid", SPHelper.getInstance().getString(Constant.USER_ID));
        params.put("sysid", SPHelper.getInstance().getString(Constant.SYS_ID));
        params.put("model", "base.mselect");
        params.put("fun", "getlastgoodscat");
        Log.i("goods", params.toString());
        LoadServer.getConnect(getApplicationContext(), Api.LOGIN, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int i, Header[] headers, byte[] bytes) {
                Log.i("login", new String(bytes));
                try {
                    JSONObject jsonObject = new JSONObject(new String(bytes));
                    JSONArray result = jsonObject.getJSONArray("result");
                    fl_Beens = new Gson().fromJson(result.toString(), new TypeToken<List<SupBeen>>() {
                    }.getType());
                } catch (JSONException e) {

                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
            }
        });

    }
    //下载
    private void downmd() {
        RequestParams params = new RequestParams();
        params.put("logid", SPHelper.getInstance().getString(Constant.USER_ID));
        params.put("sysid", SPHelper.getInstance().getString(Constant.SYS_ID));
        params.put("model", "base.mselect");
        params.put("fun", "getlastmarket");
        Log.i("goods", params.toString());
        LoadServer.getConnect(getApplicationContext(), Api.LOGIN, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int i, Header[] headers, byte[] bytes) {
                Log.i("login", new String(bytes));
                try {
                    JSONObject jsonObject = new JSONObject(new String(bytes));
                    JSONArray result = jsonObject.getJSONArray("result");
                    md_Beens = new Gson().fromJson(result.toString(), new TypeToken<List<SupBeen>>() {
                    }.getType());
                } catch (JSONException e) {

                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
            }
        });

    }
    //下载
    private void downpp() {
        RequestParams params = new RequestParams();
        params.put("logid", SPHelper.getInstance().getString(Constant.USER_ID));
        params.put("sysid", SPHelper.getInstance().getString(Constant.SYS_ID));
        params.put("model", "base.mselect");
        params.put("fun", "getlastgoodsbrand");
        Log.i("goods", params.toString());
        LoadServer.getConnect(getApplicationContext(), Api.LOGIN, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int i, Header[] headers, byte[] bytes) {
                Log.i("login", new String(bytes));
                try {
                    JSONObject jsonObject = new JSONObject(new String(bytes));
                    JSONArray result = jsonObject.getJSONArray("result");
                    pp_Beens = new Gson().fromJson(result.toString(), new TypeToken<List<SupBeen>>() {
                    }.getType());
                } catch (JSONException e) {

                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
            }
        });

    }

}
